﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using OnlineCourse.Model;
using OnlineCourse.Model.Entity;

namespace OnlineCourse.Services
{
    public class AdvertisingService:IServices.IAdvertisingServices 
    {
        private readonly ApplicationDbContext _db;
        public AdvertisingService(ApplicationDbContext db)
        {
            this._db = db;
        }
        /// <summary>
        /// 添加广告内容
        /// </summary>
        /// <param name="imagePath"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool Add(string imagePath, string url)
        {

            try
            {
                Advertising model = new Advertising();//创建一个实体对象
                model.ImagePath = imagePath;
                model.Url = url;
                _db.Advertisings.Add(model);//添加录单信息
                _db.SaveChanges();
                return true;
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        /// <summary>
        /// 删除指定广告
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public bool Delete(Guid id)
        {
            try
            {
                var m = _db.Advertisings.FirstOrDefault(p => p.Id == id);
                _db.Advertisings.Remove(m);
                _db.SaveChanges();
                return true;
            }
            catch (Exception err)
            {

                throw err;
            }
        }
        /// <summary>
        /// 按时间输出最新i条广告
        /// </summary>
        /// <returns></returns>
        public IList<Advertising> GetList(int i)
        {
            var list = _db.Advertisings.OrderByDescending(p => p.UpdatedDate).Skip(0).Take(i).ToList();
            return list;
        }
        /// <summary>
        /// 修该广告信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="imagePath"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public bool Update(Guid id, string imagePath, string url)
        {
            try
            {
                var m = _db.Advertisings.FirstOrDefault(p => p.Id==id);
                if(m!=null)
                {
                    m.ImagePath = imagePath;
                    m.Url = url;
                    _db.SaveChanges();
                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }

    }
}
